package me.monster.grideaprocessor.tool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @description
 * @author: Created jiangjiwei in 2020/11/1 10:12
 */
public class CommandUtils {
    public static void run(String command) {
        Runtime run = Runtime.getRuntime();
        try {
            Process p = run.exec(command);
            System.out.println(p.exitValue());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void runPrint(String command) {
        String s = "";
        try {
            Process p = Runtime.getRuntime().exec(command);
            InputStream is = p.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            p.waitFor();
            if (p.exitValue() != 0) {
                //说明命令执行失败,可以进入到错误处理步骤中
                System.out.println("执行失败：" + p.exitValue());
            } else {
                System.out.println("执行成功：" + p.exitValue());
            }
            while ((s = reader.readLine()) != null) {
                System.out.println(s);
            }
            reader.close();
            is.close();

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void runMore(String... commands) {
        String s = "";
        try {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < commands.length; i++) {
                sb.append(commands[i]);
                if (i != commands.length - 1) {
                    sb.append(" & ");
                }
            }
            String command = sb.toString();
            System.out.println("more command is " + command);
//            for (String command : commands) {
            Process p = Runtime.getRuntime().exec(commands);
            InputStream is = p.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            p.waitFor();
            sb.delete(0, sb.length());

            sb.append("结果如下：\n").append("返回码：").append(p.exitValue()).append('\n');
            if (p.exitValue() != 0) {
                //说明命令执行失败,可以进入到错误处理步骤中
            }
            while ((s = reader.readLine()) != null) {
//                    System.out.println(s);
                sb.append(s).append('\n');
            }
            reader.close();
            is.close();
//            }
            System.out.println(sb.toString());
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
